import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Row, Col, Select } from 'antd';
import StandardTable from '@/components/StandardTable';
import moment, { isDate } from 'moment';
import AntdForm from '@/components/AntdForm';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import AntdDatePicker from '@/components/AntdDatePicker';
import AdUpload from '@/components/AdUpload';
import { queryDictData, formatFile, vitifyCheck, queryDict, formatPrice } from '@/utils/common';
import { allDictList, billStateOnlyReadList } from '@/utils/constans';
import {
  allDispatchType,
  selectArchivesDetailAndInfo,
  renderTableAdSelect,
  codes,
  saveAllValues,
} from './utils';
import OilInfoForm from './OilInfoForm';
import FileReader from '@/components/FileReader';
import SelectForm from '@/components/SelectForm';
import SearchSelect from '@/components/SearchSelect';
import { columns1 } from '@/pages/Common/common';
import styles from './archives.less';

const { Option } = Select;

@connect(({ Archives, component, loading }) => ({
  dictObject: component.dictObject,
  oilBindInfoList: Archives.oilBindInfoList,
  bindLoading: loading.effects[allDispatchType.oilBindInfoList],
  // formValues: Archives.formValues,
}))
@Form.create()
export default class OilInfoBind extends Component {
  state = {
    selectedRows: [],
    bindSelectedRows: [],
    type: '',
    cars: [],
    formValues: {},
  };
  className = 'archives-table-info';

  componentDidMount() {
    const { archivesId, oilBindInfoList } = this.props;
    if (!oilBindInfoList[archivesId]) this.oilBindInfoList();
  }

  componentWillMount() {
    const allDict = [allDictList.oilType, allDictList.saleCompany];
    queryDict({ props: this.props, allDict });
  }

  componentWillReceiveProps(nextProps, nextState) {
    const { visibleBindOil } = nextProps;
    if (this.props.visibleBindOil !== visibleBindOil && visibleBindOil) {
      this.oilBindInfoList();
    }
  }
  oilBindInfoList = (param = {}) => {
    const { dispatch, archivesId, cars } = this.props;
    param.archivesId = archivesId;
    dispatch({
      type: allDispatchType.oilBindInfoList,
      payload: {
        vehicleId: cars ? cars[0].id : '',
        ...param,
      },
    });
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  oilBindColumns = [
    {
      title: '单据号',
      dataIndex: 'oilNo',
      // render: (text, record) => this.renderInfo(text, record),
    },
    {
      title: '状态',
      dataIndex: 'billStatus',
      render: (text, record) => (
        <AdSelect
          onlyRead={true}
          value={text ? text : record.status}
          data={billStateOnlyReadList}
        />
      ),
    },
    {
      title: '主车牌',
      dataIndex: 'cartPlateNo',
    },
    {
      title: '加油时间',
      dataIndex: 'oilTime',
    },
    {
      title: '加油站',
      dataIndex: 'oilSiteName',
      render: text =>
        renderTableAdSelect({ props: this.props, value: text, key: allDictList.saleCompany }),
    },
    {
      title: '加油方式',
      dataIndex: 'oilType',
      render: text =>
        renderTableAdSelect({ props: this.props, value: text, key: allDictList.oilType }),
    },
    {
      title: '加油量（L）',
      dataIndex: 'oilAmount',
    },
    {
      title: '单价',
      dataIndex: 'price',
      render: text => <span>{formatPrice(text)}</span>,
    },
  ];

  //关联加油
  handleOkBindOil = () => {
    const { dispatch, setOilBindInfoModal, archivesId } = this.props;
    const { bindSelectedRows } = this.state;
    if (bindSelectedRows.length === 0) return;

    dispatch({
      type: allDispatchType.oilBindInfoOperate,
      payload: { ids: bindSelectedRows.map(v => v.id), archivesId },
      callback: data => {
        if (!data) return;
        setOilBindInfoModal();
        this.oilInfoList(archivesId);
      },
    });
  };
  oilInfoList = (param = {}) => {
    const { dispatch, archivesId } = this.props;
    param.id = archivesId;
    dispatch({
      type: allDispatchType.oilInfoList,
      payload: {
        ...param,
      },
    });
  };

  // 重置
  handleFormReset = () => {
    // console.log('this.props', this.props);
    const { form } = this.props;
    const props = { props: this.props };
    this.setState({
      cars: [],
      formValues: {},
    });
    form.resetFields();
    saveAllValues({ payload: { formValues: {} }, ...props });
    this.oilBindInfoList();
  };

  // 查询
  handleSearch = formValues => {
    // if (!formValues) return;
    const { cars } = this.state;
    const { vehicleId, oilTime, ...param } = formValues;
    if (oilTime&&oilTime.length>0) {
      param.oilStartTime = moment(oilTime[0]).format(dateFormat);
      param.oilEndTime = moment(oilTime[1]).format(dateFormat);
    }else{
      param.oilStartTime=''
      param.oilEndTime=''
    }
    if (cars.length > 0) {
      const vehicleId = cars.map(v => {
        return v.id;
      });
      param.vehicleId = vehicleId.join(',');
    } else {
      param.vehicleId = '';
    }
    this.setState({
      formValues: param,
    });
    const params = { props: this.props, payload: param };
    saveAllValues({ payload: { formValues: param }, props: this.props });
    this.oilBindInfoList(param);
  };

  // 分页操作
  handleStandardTableChangeBind = param => {
    // const { formValues } = this.props;
    const { formValues } = this.state;
    console.log('formValues', formValues, 'param', param);
    this.oilBindInfoList({ ...formValues, ...param });
  };
  handleStandardTableChange = param => {
    this.oilInfoList(param);
  };
  getValue = values => {
    this.setState({
      cars: values,
    });
  };
  //选中加油关联数据：
  selectedRows = () => {};

  render() {
    const { oilBindInfoList, form, bindLoading, dictObject, cars, getBindRows } = this.props;

    const { bindSelectedRows } = this.state;
    const commonParams = {
      getFieldDecorator: form.getFieldDecorator,
    };
    const firstFormItem = (
      <AntdFormItem label="车牌号" code="vehicleId" {...commonParams}>
        <SearchSelect
          dataUrl="tms/tms-oil/selectOilVehicle"
          url="tms/tms-oil/selectOilVehicleView_s" // selectedData只只有id时需要传url
          selectedData={cars} // 选中值
          multiple={false} // 是否多选
          showValue="cartPlateOneNo"
          searchName="cartPlate"
          columns={columns1} // 表格展示列
          onChange={values => this.getValue(values, 'cars')} // 获取选中值
          scrollX={480}
          id="tmsOil_1"
          allowClear={true}
          disabled={true}
        />
      </AntdFormItem>
    );

    const secondFormItem = (
      <AntdFormItem label="加油方式" code="oilType" {...commonParams}>
        <Select placeholder="请选择" allowClear={true}>
          {dictObject[allDictList.oilType] &&
            dictObject[allDictList.oilType].map(item => (
              <Option key={item.code}>{item.value}</Option>
            ))}
        </Select>
      </AntdFormItem>
    );

    // secondForm 参数
    const otherFormItem = [
      [
        <AntdFormItem label="加油站" code="oilSiteName" {...commonParams}>
          <AntdInput placeholder="请输入加油站" />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem label="加油时间" code="oilTime" {...commonParams}>
          <AntdDatePicker mode="range" />
        </AntdFormItem>,
        'operatorButtons',
      ],
    ];

    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: expandForm => {
        this.handleStateChange([{ expandForm }]);
      },
      code: codes.select,
    };
    return (
      <Fragment>
        <div className="archives_oilInfo">
          <SelectForm {...selectFormParams} />
          <StandardTable
            loading={bindLoading}
            selectedRows={bindSelectedRows}
            onSelectRow={bindSelectedRows => {
              this.handleStateChange([{ bindSelectedRows }]);
              getBindRows(bindSelectedRows);
            }}
            scrollY={300}
            data={oilBindInfoList || {}}
            columns={this.oilBindColumns}
            scrollX={2000}
            onPaginationChange={this.handleStandardTableChangeBind}
          />
        </div>
      </Fragment>
    );
  }
}
